package club.dingzm.myapplication;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSONObject;
import com.yanzhenjie.permission.runtime.Permission;

import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;

import club.dingzm.myapplication.HttpBreakPoint.BreakpointInfo;
import club.dingzm.myapplication.WebSocketUtils.WsUploadFileManager;

/**
 * 使用 websocket 进行断点续传文件
 *  主要内容使用的是 WsUploadFileManager 上
 */
public class WebScoektDemoActivity extends Activity {

    // 需要用到的各个控件对象
    private Button btnConnectDevice = null;
    private Button print = null;
    private TextView tv_progress = null;

    private Timer timer ;
    private String cacheId = "";
    private String filePath = "";
//    private WebSocketBreakpointUtil webSocketBreakpointUtil = new WebSocketBreakpointUtil();
    private WsUploadFileManager wsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.websocket_demo);
        //授权进行
        String[] PERMISSIONS_STORAGE = {
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,"android.permission.INSTALL_PACKAGES" };
        int permission = ActivityCompat.checkSelfPermission(WebScoektDemoActivity.this,"android.permission.INSTALL_PACKAGES");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(WebScoektDemoActivity.this,PERMISSIONS_STORAGE,3);
        }

        btnConnectDevice = (Button) findViewById(R.id.btn_printer);
        btnConnectDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSocket(v);
            }
        });
        //缓存Id,传入 工具类里面，每次调用成功之后，缓存当前进度
        cacheId = "id11414214214";
        filePath = "/storage/emulated/0/Download/Spring Boot+Vue.pdf";
        print=(Button)findViewById(R.id.btn_dayin);
        print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSocket(v);
            }
        });
        tv_progress= findViewById(R.id.tv_progress);
        wsManager = WsUploadFileManager.getInstance();
    }

    // 选择开始传输数据
    public void startSocket(View view) {

        wsManager.init("userId",cacheId);
        if ( SPUtil.contains(this, cacheId) ) {
            String id = (String) SPUtil.get(getApplicationContext(), cacheId, "");
            BreakpointInfo info = JSONObject.parseObject(id,BreakpointInfo.class);
            //如果 缓存数据为空 则重新上传 文件
            if ( id == null || id == "" || info == null){
                wsManager.initSendFile(getApplicationContext(),filePath ,cacheId);
                wsManager.startSendFile();
            }else{
                info.setFilePath(info.getFilePath());
                wsManager.initSendFile(getApplicationContext(),info,cacheId);
                wsManager.startSendFile();
            }
        }else{
            wsManager.initSendFile(getApplicationContext(),filePath ,cacheId);
            wsManager.startSendFile();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                BreakpointInfo info = wsManager.getInfo();
                System.out.println("文件大小："+info.getFileLength());
                System.out.println("文件已上传大小："+ info.getCurrentBlock() * BreakpointInfo.CHUNK_SIZE );
                BigDecimal bg = new BigDecimal(0);
                if ( info.getFileLength() != 0){
                    bg = new BigDecimal( info.getCurrentBlock() * 100.0 / info.getBLOCK_SIZE());
                }
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                System.out.println(""+f1+"%");
                tv_progress.setText( ""+f1+"%" );
                if (wsManager.getStopFlag()){
                    timer.cancel();
                }
            }
        }, 0 , 5000);

    }

    /**
     * 选择 停止传输数据
     * @param view
     */
    public void stopSocket(View view) {
        timer.cancel();
        wsManager.setStop(true);
        timer = new Timer();
        //这个任务执行一次
        timer.schedule(new TimerTask() {
            public void run() {
                BreakpointInfo info = wsManager.getInfo();
                System.out.println("文件大小："+info.getFileLength());
                System.out.println("文件已上传大小："+ info.getCurrentBlock() * BreakpointInfo.CHUNK_SIZE );

                //获取最终的进度情况
                BigDecimal bg = new BigDecimal(0);
                if ( info.getFileLength() != 0){
                    bg = new BigDecimal( info.getCurrentBlock() * 100.0 / info.getBLOCK_SIZE());
                }
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                tv_progress.setText( ""+f1+"%" );
                String infoStr = JSONObject.toJSONString(info);
                System.out.println("当前已上传文件信息："+infoStr);
//                SPUtil.put(getApplicationContext(), cacheId, infoStr);
                if (wsManager.getStopFlag()){
                    timer.cancel();
                }
            }
        }, 1000 );

    }

    @Override
    protected void onDestroy() {
        System.out.println("进入onDestroy");
        timer.cancel();
        wsManager.setStop(true);
        //获取最终的进度情况
        BreakpointInfo info = wsManager.getInfo();

        String infoStr = JSONObject.toJSONString(info);
        SPUtil.put(getApplicationContext(), cacheId, infoStr);
        System.out.println("当前已上传文件信息："+infoStr);
        System.out.println("销毁前写入缓存");
        super.onDestroy();
    }

    
}